import 'package:better_player_plus/better_player_plus.dart';
import 'package:flutter/material.dart';

class MyCustomVideoPlayerWidget extends StatefulWidget {
  final String videoUrl;
  final bool showController;
  final bool autoPlay;
  final ValueChanged<BetterPlayerController>? controlCall;

  const MyCustomVideoPlayerWidget({
    super.key,
    required this.videoUrl,
    this.showController = true,
    this.autoPlay = true,
    this.controlCall,
  });

  @override
  State<MyCustomVideoPlayerWidget> createState() => _MyCustomVideoPlayerWidgetState();
}

class _MyCustomVideoPlayerWidgetState extends State<MyCustomVideoPlayerWidget> with AutomaticKeepAliveClientMixin {
  late String videoUrl = widget.videoUrl;

  late bool showControls = widget.showController;
  late bool autoPlay = widget.autoPlay;

  late BetterPlayerController _betterPlayerController;

  late BetterPlayerDataSource betterPlayerDataSource = BetterPlayerDataSource(BetterPlayerDataSourceType.network, widget.videoUrl);

  @override
  void initState() {
    super.initState();
    init();
    widget.controlCall?.call(_betterPlayerController);
  }

  void init() async {
    _betterPlayerController = BetterPlayerController(
      _betterPlayerConfiguration(),
      betterPlayerDataSource: BetterPlayerDataSource(BetterPlayerDataSourceType.network, widget.videoUrl),
    );
  }

  BetterPlayerConfiguration _betterPlayerConfiguration() {
    return BetterPlayerConfiguration(
      aspectRatio: 16 / 9,
      autoPlay: autoPlay,
      useRootNavigator: false,
      controlsConfiguration: BetterPlayerControlsConfiguration(
        showControlsOnInitialize: false,
        enableMute: false,
        enableSkips: false,
        showControls: showControls,
        playerTheme: BetterPlayerTheme.material,
        controlBarColor: Colors.black38,
        enableOverflowMenu: false,
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return BetterPlayer(controller: _betterPlayerController);
  }

  @override
  dispose() {
    super.dispose();
  }

  @override
  bool get wantKeepAlive => true;
}
